import GameData from './GameData';
import Utils from './utils/Utils';

const { ccclass, property } = cc._decorator;

@ccclass
export default class UsdPrefab extends cc.Component {


    @property(cc.Sprite)
    sprite: cc.Sprite = null;

    private xPos: number;
    private yPos: number;
    private xVel: number;
    private yVel: number;
    private oScale: number;
    private gravity: number = 0.05;

    public maxR: number = 0;
    private isZ: boolean;
    /**类型 */
    public type: number = 0;
    private data: any = {};

    start() {

    }

    /**初始化数据 */
    public initData(xPos, yPos, xVel, yVel, oScale, spriteFrame) {
        this.data = { xPos, yPos, xVel, yVel, oScale }
        this.xPos = xPos;
        this.yPos = yPos;
        this.yVel = yVel;
        this.xVel = xVel;
        this.oScale = oScale;
        this.gravity = Utils.limit(0.05, 0.1);
        this.type = Math.ceil(Math.random() * 3);
        // let texture: string = `ui/usd/usd${GameData.gameType}_${this.type}`;
        // console.log(texture,this.xPos,this.yPos)
        this.sprite = this.node.getComponent(cc.Sprite);
        // Utils.loadSpeite(texture, this.sprite);
        this.sprite.spriteFrame = spriteFrame;
        this.node.opacity = 170;
        this.node.scale = oScale;

        // this.width = 150 * this.oScale;
        // this.height = 150 * this.oScale;

        this.upPoint();

        this.node.angle = Utils.limit(0, 360);
        let r: number = this.node.angle;
        this.isZ = this.xVel > 0;
        this.maxR = this.isZ ? Utils.limit(r, r + 30) : Utils.limit(r, r - 30);
    }


    private upPoint() {
        this.node.x = this.xPos;
        this.node.y = this.yPos;
    }


    public update(dt) {
        this.upPoint();
        let self = this;
        self.yVel -= self.gravity;
        self.yPos += self.yVel;
        self.xPos += self.xVel;
        if (this.maxR < 0) {
            this.node.angle = this.node.angle > this.maxR ? this.maxR : this.node.angle += 1;
        } else {
            this.node.angle = this.node.angle < this.maxR ? this.maxR : this.node.angle -= 1;
        }

        if (this.node.y < -(cc.winSize.height / 2 + 100)) {
            this.resetData();
        }
    }

    public resetData() {
        this.xPos = this.data.xPos;
        this.yPos = this.data.yPos;
        this.xVel = this.data.xVel;
        this.yVel = this.data.yVel;
        this.oScale = this.data.oScale;
    }


    /**重置 */
    public reset() {
        this.sprite.spriteFrame = null;
        this.xPos = null;
        this.yPos = null;
        this.xVel = null;
        this.yVel = null;
        this.oScale = null;
        this.maxR = null;
        this.isZ = null;
        this.node.scale = 1;
        this.node.x = this.node.y = 0;

    }
    // update (dt) {}
}
